<html>
  <head>   
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAqwwIT8aSIQ03hXvYlXzOvRZ08Rv7LWDQ&sensor=false"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/annyang/1.1.0/annyang.min.js"></script>
    <script src="http://connect.soundcloud.com/sdk.js"></script>
    <script src="https://w.soundcloud.com/player/api.js"></script>
    <style type="text/css">
      html { height: 100% }
      body { background: #e74c3c; color: white; font-size: 14pt; font-family: "Lato", "Helvetica Neue", "Helvetica", sans-serif; height: 100%; margin: 0; padding: 0; margin: 20px 50px;}
      #map-canvas {
        display:none;
      }
      #container {
        margin-bottom: 30px;
      }
      .code {
        font-family: monospace;
        color: #666;
        border: 1px solid #ddd;
        padding: 10px;
        background: #fff;
        -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1), 0 0 40px rgba(0, 0, 0, 0.05) inset;
        -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1), 0 0 40px rgba(0, 0, 0, 0.05) inset;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1), 0 0 40px rgba(0, 0, 0, 0.05) inset;
        margin-bottom: 10px;
      }
      h1 {
        display: inline-block;
      }
      h2 {
        font-size: 50px;
        margin-bottom: -10px;
        font-weight: lighter;
      }
      a {
        color: #f1c40f;
        font-weight: bold;
      }
      a:hover {
        cursor: pointer;
      }
      footer {
        position: relative;
        bottom: 0;
        padding-top: 10px;
        margin-bottom: 20px;
      }
    </style>
  </head>
  <body>
    <div id="main">
      <h1>OK Hangout</h1> (<a onClick="toggleDescription()">toggle help</a>)
      <div id="description">
        <p>
          Use voice commands during a Google Hangout to share quick and seamless queries.
        </p>
        <p>
          Try saying "OK Hangout"
        </p>
        <div class="code">
          // More Voice Commands
          <br>
          Show me [query]: Display images
          <br>
          Where is [location]: Drop a pin on a Google map
          <br>
          Watch [query]: Open Youtube video
          <br>
          Listen [song]: Play a song using Soundcloud
          <br>
          Calculate [expression]: Supports multiplication, division, addition, subtraction
          <br>
          Define [word]: Show definition
          <br>
          Synonym for [word]: Show synonyms
          <br>
          Cook [word]: Display recipe
        </div>
      </div>
      <div id="container"></div>
      <div id="map-canvas" style="width:800px;height:500px;"></div>
    </div>
    <footer>-----<br>Hacked by <a href="http://twitter.com/whatmariel">@whatmariel</a> and <a href="http://twitter.com/alexa_claire">@alexa_claire</a> at PearlHacks</footer>
    <script>

      var geocoder;
      var map;
      var tutorial = true;

      function toggleDescription() {
        $("#description").fadeToggle();
      }

      function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }

      function clear() {
        $("#description").hide();
        $("#map-canvas").hide();
        $("#container").empty();
      }

      function locate(location) {
        clear();
        console.log("locate: " + location);
        $("#map-canvas").fadeIn();
        $("#container").append("<h2>" + location + "<h2>");
        geocoder.geocode( { 'address': location}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
          } else {
            console.log('Geocode was not successful for the following reason: ' + status);
          }
        });
        google.maps.event.trigger(map, "resize");
      }

      google.maps.event.addDomListener(window, 'load', initialize);

      function evaluate(expression) {
        clear();
        console.log("evaluate: " + expression);
        var re = /^(\d+) (\-|X|divided by|\+|times|plus|minus)\s?(\d+)$/;
        var exArr = expression.match(re);
        var operator;
        switch(exArr[2]) {
          case "X":
            operator = "*";
            break;
          case "times":
            operator = "*";
            break;
          case "divided by":
            operator = "/";
            break;
          case "plus":
            operator = "+";
            break;
          case "-":
            operator = "-";
            break;
          case "minus":
            operator = "-";
            break;
        }
        var expression = exArr[1] + operator + exArr[3];
        var answer = eval(expression);
        $("#container").append("<div id='calculator'>Calculate '" + expression + "' :  " + answer + "</div>").fadeIn();
      }

      if (annyang) {
        var showFlickr = function(tag) {
          clear();
          $("#container").append("<div id='flickrLoader'><p></p></div><div id='flickrGallery'></div>")
          $('#flickrLoader p').text('Searching for '+tag).fadeIn('fast');
          var url = '//api.flickr.com/services/rest/?method=flickr.photos.search&api_key=a828a6571bb4f0ff8890f7a386d61975&sort=interestingness-desc&per_page=9&format=json&callback=jsonFlickrApi&tags='+tag;
          $.ajax({
            type: 'GET',
            url: url,
            async: false,
            jsonpCallback: 'jsonFlickrApi',
            contentType: "application/json",
            dataType: 'jsonp'
          });
        };

        var jsonFlickrApi = function(results) {
          $('#flickrLoader p').fadeOut('slow');
          var photos = results.photos.photo;
          $('flickrGallery').empty();
          $.each(photos, function(index, photo) {
            $(document.createElement("img"))
              .attr({ src: '//farm'+photo.farm+'.staticflickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg' })
              .addClass("flickrGallery")
              .appendTo(flickrGallery);
          });
        };

        var okPerson = function() {
          console.log("OK, Human");
          clear();
          $("#container").append("<div id='okperson'>OK, Human.</div>").fadeIn();
        };

        var watch = function(query) {
          clear();
          console.log("watch: " + query);
          $("#container").append('<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/?listType=search&autoplay=1&list=' + query + '" frameborder="0" allowfullscreen></iframe><div id="playlist"></div>');
        };

        var define = function(query) {
          clear();
          console.log("define: " + query);
          $.ajax({
            url: 'https://api.pearson.com/v2/dictionaries/entries?headword=' + query + '&apikey=qfw3wC8nsZJhmF97mK2ywPmgZCpIxPBu', 
            type: 'GET',
            dataType: 'json',
            success: function(data) {
              var word = data['results'][0]['senses'][0];
              $("#container").append("<div><strong>Definition:</strong> " + (word.definition !== undefined ? word.definition : '') + "</br></br><div><strong>Example: </strong> " + (word.examples[0].text !== undefined ? word.examples[0].text : '') + "</div>");
                
            }
          });
        };

        var synonym = function(query) {
          clear();
          console.log("synonym: " + query);
          $.ajax({
            url: 'http://words.bighugelabs.com/api/2/38e36cde2d19f45d5a1e4e686f12b7d7/' + query + '/json',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
              for (key in data) {
                var ary = data[key].syn;
                for (word in ary) {
                  $("#container").append(ary[word] + "</br>");
                }
              }
            }
          });
        };

        var recipe = function(query) {
          clear();
          console.log("recipe: " + query);
          $.ajax({
            url: 'https://api.pearson.com/v2/foodanddrink/recipes?search=' + query,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
              var recipe = data['results'][0];
              if (recipe !== undefined) {
                $("#container").append('<strong>Ingredients:</strong></br>');
                var ingredients = recipe.ingredients;
                for (i in ingredients) {
                  $("#container").append(ingredients[i].description + '</br>');
                }
                $("#container").append('</br></br><strong>Directions: </strong></br>' + recipe.directions.join('</br>'))
              }
            }
          });
        };

        SC.initialize({
          client_id: '42a4426020b57d83c51a76d65856cca8'
        });

        function replaceSoundcloud(track_url) {
          SC.oEmbed(track_url, { auto_play: true, maxheight: 200, maxwidth: 800 }, function(oEmbed) {
            $("#soundcloud").html(oEmbed.html).fadeIn();
          });
        }

        function soundcloud(query) {
          clear();
          console.log("soundcloud: " + query);
          var track_url;
          SC.get('/tracks', { q: query }, function(tracks) {
            console.log(tracks[0]);

            track_url = tracks[0].permalink_url;
            SC.oEmbed(track_url, { auto_play: true, maxheight: 200, maxwidth: 800 }, function(oEmbed) {
              $("#container").append("<div id='soundcloud'>" + oEmbed.html + "</div>");
              $("#container").append("</div><div id='soundcloud_results'><br>Results:");
              for (var i = 0; i < tracks.length; i++) {
                $("#container").append("<br><a onClick=replaceSoundcloud('" + tracks[i].permalink_url + "')>" + tracks[i].title + "</a>")
              }
              $("#container").append("</div>");
            });
          });
        }

        // Let's define a command.
        var commands = {
          'ok hangout': okPerson, 
          'show me *term': showFlickr,
          'where is *location': locate,
          'calculate *expression': evaluate,
          'watch *term': watch,
          'listen *query': soundcloud,
          'define *term': define,
          'synonym for *term': synonym,
          'cook *term': recipe
        };
        // Add our commands to annyang
        annyang.addCommands(commands);

        // Start listening.
        annyang.start();
      }
    </script>

  </body>
</html>